const Values = require('../template')

// 异步场景测试单独封装
async function testAsyncComplexScenarios() {
  // 1. 异步+转换+验证组合获取值
  const asyncComboResult = await (() => {
    const obj = {
      user1: { name: 'Alice', score: '95' },
      user2: { name: 'Bob', score: '82' },
      user3: { name: 'Charlie', score: '76' },
      user4: { name: 'Dave', score: 'invalid' }
    }
    // 流程：1.异步转换（字符串分数转数字）→ 2.验证（分数≥80）
    const processor = async (user) => {
      await new Promise(resolve => setTimeout(resolve, 0))
      // 转换：分数转数字，无效值设为-1
      const score = !isNaN(Number(user.score)) ? Number(user.score) : -1
      return { ...user, score }
    }
    const schema = { score: { type: 'number', min: 80 } }

    return Values.valuesAsync(obj, processor)
      .then(transformedUsers => Values.valuesWithValidation({ data: transformedUsers }, 'data'))
      .then(validUsers => {
        // 验证：只保留score≥80的用户（Alice、Bob）
        return validUsers.length === 2 &&
          validUsers.some(u => u.name === 'Alice' && u.score === 95) &&
          validUsers.some(u => u.name === 'Bob' && u.score === 82)
      })
  })()

  console.log("4. 异步+转换+验证组合获取值:", asyncComboResult)

  // 2. 并发处理复杂嵌套对象值
  const concurrentComplexResult = await (() => {
    const obj = {
      products: Array.from({ length: 50 }, (_, i) => ({
        id: i,
        info: { name: `Product${i}`, price: 100 + i },
        stock: Math.floor(Math.random() * 100)
      }))
    }
    // 并发处理：1.价格加10 → 2.筛选库存≥30的商品
    const processor = async (product) => {
      await new Promise(resolve => setTimeout(resolve, 0))
      return { ...product, info: { ...product.info, price: product.info.price + 10 } }
    }
    const concurrency = 4

    return Values.valuesConcurrent(obj, processor, concurrency)
      .then(processedData => {
        const products = processedData.find(item => Array.isArray(item)) || []
        const filtered = Values.valuesWithFilter({ products }, (p) => p.stock>= 30)
        return filtered.length<= 50 && filtered.every(p => p.info.price === 110 + p.id)
      })
  })()

  console.log("5. 并发处理复杂嵌套对象值:", concurrentComplexResult)
}

function testValuesComplexScenarios() {
  // 1. 深度嵌套+多条件过滤组合
  console.log(
    "1. 深度嵌套+多条件过滤组合:",
    (() => {
      const obj = {
        school: {
          grade1: {
            classA: { students: [{ name: 'Tom', age: 10 }, { name: 'Lily', age: 11 }] },
            classB: { students: [{ name: 'Jack', age: 9 }, { name: 'Lucy', age: 12 }] }
          },
          grade2: {
            classA: { students: [{ name: 'Mike', age: 12 }, { name: 'Emma', age: 11 }] }
          }
        }
      }
      // 流程：1.深度获取所有值（深度4）→ 2.筛选学生数组 → 3.提取学生并过滤年龄≥11
      const deepValues = Values.valuesDeep(obj, 4)
      const studentArrays = Values.valuesWithFilter({ data: deepValues }, (val) => Array.isArray(val) && val[0]?.name)
      const allStudents = studentArrays.flat()
      const olderStudents = Values.valuesWithFilter({ students: allStudents }, (s) => s.age >= 11)

      return olderStudents.length === 4 &&
        olderStudents.some(s => s.name === 'Lily') &&
        olderStudents.some(s => s.name === 'Lucy') &&
        olderStudents.some(s => s.name === 'Mike') &&
        olderStudents.some(s => s.name === 'Emma')
    })()
  )

  // 2. 类型+正则+排序组合筛选
  console.log(
    "2. 类型+正则+排序组合筛选:",
    (() => {
      const obj = {
        log1: { type: 'error', message: 'Login failed' },
        log2: { type: 'info', message: 'User logged in' },
        log3: { type: 'error', message: 'Database connection failed' },
        log4: { type: 'warn', message: 'Low memory' },
        log5: { code: 500, message: 'Server error' } // 无type属性
      }
      // 流程：1.筛选有type属性的日志 → 2.筛选type为error的日志 → 3.按message长度排序
      const hasTypeLogs = Values.valuesWithFilter(obj, (log) => log.type)
      const errorLogs = Values.valuesWithType({ logs: hasTypeLogs }, 'error')
      const sortedLogs = Values.valuesWithSort({ logs: errorLogs }, (a, b) => a.message.length - b.message.length)

      return sortedLogs.length === 2 &&
        sortedLogs[0].message === 'Login failed' &&
        sortedLogs[1].message === 'Database connection failed'
    })()
  )

  // 3. 循环引用对象安全取值
  console.log(
    "3. 循环引用对象安全取值:",
    (() => {
      const obj = { a: 1, b: 2 }
      obj.self = obj // 循环引用
      try {
        const result = Values.values(obj)
        // 结果应包含1、2、obj自身，排除循环引用导致的死循环
        return result.length === 3 && result.includes(1) && result.includes(2) && result.includes(obj)
      } catch (e) {
        return false // 不应抛出错误
      }
    })()
  )
}

// 执行复杂场景测试（先同步后异步）
console.log("=== Values 复杂场景测试 ===")
testValuesComplexScenarios()
testAsyncComplexScenarios() // 异步场景单独执行
console.log("=== Values 复杂场景测试完成 ===")
